package com.apptravel.util;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class DateJsonValueProcessor implements JsonValueProcessor {
	public static Logger log = Logger.getLogger(DateJsonValueProcessor.class);
	
	public static final String Default_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
	private DateFormat dateFormat;

	public DateJsonValueProcessor() {
		dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);
	}
	
	public DateJsonValueProcessor(String datePattern) {
		if(StringUtils.isEmpty(datePattern))
			dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);
		else
			dateFormat = new SimpleDateFormat(datePattern);
	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	private Object process(Object bean) {
		String result = "";
		log.info("bean instanceof java.sql.Date >>"+ (bean instanceof java.sql.Date)+ " .");
		log.info("bean instanceof java.sql.Timestamp >>"+ (bean instanceof java.sql.Timestamp)+ " .");
		log.info("bean instanceof java.util.Date >>"+(bean instanceof Date)+ " .");
		//log.info("bean instanceof java.util.Date >>"+(bean instanceof oracle.sql.TIMESTAMP)+ " .");
		
		if (bean instanceof java.sql.Date) {
			result = dateFormat.format((java.sql.Date) bean);
		}
		else if (bean instanceof java.sql.Timestamp) {
			result = dateFormat.format((java.sql.Timestamp) bean);
		}
		else if (bean instanceof Date) {
			result = dateFormat.format((Date) bean);
		} 
		/*else if (bean instanceof oracle.sql.TIMESTAMP) {
			try {
				result = dateFormat.format(((oracle.sql.TIMESTAMP) bean).dateValue());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} */
		log.info(result);
		return result;

	}
}
